package org.light.framework.util;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

/**
 * JSON转换类
 * @author de.cel
 *
 */
public class JsonUtil {

	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	public static <T> String toJson(T obj) {
		String json = null;
		try {
			json=OBJECT_MAPPER.writeValueAsString(obj);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return json;
	}
	
	public static <T> List<T> toList(String jsonStr,Class<T> cls){
		
		try {
			return OBJECT_MAPPER.readValue(jsonStr, OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, cls));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return new ArrayList<T>();
	}

	public static <T> T fromJson(String json, Class<T> type) {

		T obj = null;
		try {
			obj = OBJECT_MAPPER.readValue(json, type);
		} catch (Exception e) {
			// TODO: handle exception
		}

		return obj;
	}
}
